package com.simon.nvwo.modules.web.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤器是实现了{@link javax.servlet.Filter} 接口的服务器端程序，主要用于过滤字符串编码、做业务逻辑判断
 * @author zhaoyi
 *
 */
public class FilterDemo implements Filter{
	
	//过滤器配置
	private FilterConfig config=null;
	
	//使用过滤器配置来初始化创建过滤器
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
		this.config=filterConfig;
System.out.println("过滤器初始化成功...");
		
	}
	
	/**
	 * 过滤器处理请求，完成后传递给过滤器串继续处理
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		//强制类型转换
		HttpServletRequest req=(HttpServletRequest) request;
		
		HttpServletResponse res=(HttpServletResponse) response;
		
		//设置编码类型为配置文件设置的编码类型
		req.setCharacterEncoding(config.getInitParameter("charset"));
		res.setContentType(config.getInitParameter("contentType"));
		res.setCharacterEncoding(config.getInitParameter("charset"));
		
		chain.doFilter(req, res);
		
	}
	
	/**
	 * 过滤器销毁方法
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
System.out.println("过滤器准备销毁...");		
	}
	
	

}
